#!/usr/bin/env bash

read -r -d '' ASANFLAGS <<- EOF
-fsanitize=address,undefined
-fsanitize-recover=address,undefined
-fno-sanitize=vptr,float-divide-by-zero
-fno-omit-frame-pointer
EOF
ASANFLAGS="$(echo "${ASANFLAGS}" | tr '\n' ' ')"

: ${BUILD_DIR="clang-ubsan-build"}
: ${R_HOME="$(R RHOME)"}

mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"
cmake ../cpp                         \
    -DLIBR_HOME="${R_HOME}"          \
    -DCMAKE_BUILD_TYPE="Debug"       \
    -DCMAKE_C_COMPILER=clang         \
    -DCMAKE_CXX_COMPILER=clang++     \
    -DCMAKE_C_FLAGS="${ASANFLAGS}"   \
    -DCMAKE_CXX_FLAGS="${ASANFLAGS}" \
    "$@"
cd ..

cmake --build "${BUILD_DIR}" -- "${MAKEFLAGS}"
